var db = require('../model');
var utils = require('../utils');
var uuid = require('node-uuid');
var path = require('path');
var fs = require('fs-extra');

module.exports = {
  upload: function(req, res, next) {
    var base64 = decodeURIComponent(req.body.data);
    var uid = req.decoded.data._id;
    var date = new Date();
    var url = 'simg/' + date.getYear() + date.getMonth() + '/' + uuid.v1() + '.PNG';
    var filepath = process.cwd() + '/public/' + url;
    var bitmap = new Buffer(base64, 'base64');
    var dir = path.dirname(filepath);
    fs.ensureDirSync(dir);
    fs.writeFileSync(filepath, bitmap);
    db.user.findOne({
      _id: uid
    }).then((ret) => {
      var img = new db.images({
        uid: ret.id,
        url: isDev ? 'http://' + config.domain + ':' + config.port + '/public/' + url : 'http://'+config.domain+ '/public/' +url,
        created_at: Date.now()
      });
      img.save().then((ret) => {
        res.json(utils.formatResult(ret));
      },
      next);
    },
    next);
  }
};

